from functools import partial
import subprocess

subprocess.Popen = partial(subprocess.Popen, encoding='utf-8')

import execjs
import requests
import re
import time
import random
import uuid
from urllib.parse import quote


def req_media(media_url):
    data = {
        'spm_id_from': '333.337.search - card.all.click',
        'vd_source': '69181b959bc0cae8de15caffd47134a6'
    }
    res = session.get(media_url, params=data)
    aid = re.search('"aid":(\d+),', res.text).group(1)
    cid = re.search('"cid":(\d+),', res.text).group(1)
    return aid, cid


def req_v2(aid, cid):
    v2_url = 'https://api.bilibili.com/x/player/v2'
    data = {
        'aid': aid,
        'cid': cid,
    }
    session.get(v2_url, params=data)
    session.cookies['CURRENT_FNVAL'] = '4048'


def set_b_lsid():
    t = hex(int(time.time() * 1000)).upper().replace('0X', '')

    s = ''
    for i in range(8):
        s += hex(int(16 * random.random())).upper().replace('0X', '')
    if len(s) < 8:
        s.rjust(8, '0')
    session.cookies['b_lsid'] = s + '_' + t


def set_uuid():
    session.cookies['_uuid'] = str(uuid.uuid4())


def set_buvid4():
    spi_url = 'https://api.bilibili.com/x/frontend/finger/spi'
    res = session.get(url=spi_url)
    b_4 = res.json()['data']['b_4']
    b_4 = quote(b_4)
    session.cookies['buvid4'] = b_4


def set_buvid_fp():
    with open('buvid_fp.js', 'r', encoding='utf-8') as f:
        js = execjs.compile(f.read())
    t = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36falsezh-CN24841920,10801920,1032-480Asia/Shanghaitruetruetruefalsetruenot availableWin32PDF Viewer,Portable Document Format,application/pdf,pdf,text/pdf,pdf,Chrome PDF Viewer,Portable Document Format,application/pdf,pdf,text/pdf,pdf,Chromium PDF Viewer,Portable Document Format,application/pdf,pdf,text/pdf,pdf,Microsoft Edge PDF Viewer,Portable Document Format,application/pdf,pdf,text/pdf,pdf,WebKit built-in PDF,Portable Document Format,application/pdf,pdf,text/pdf,pdfcanvas winding:yes,canvas fp::image/png;base64,iVBORw0KGgoAAAANSUhEUg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iaKAfgUAln4PyQAFzCgAsMxYTaIooF+B/wGUsPWmkr+6+QAAAABJRU5ErkJggg==,extensions:ANGLE_instanced_arrays;EXT_blend_minmax;EXT_color_buffer_half_float;EXT_disjoint_timer_query;EXT_float_blend;EXT_frag_depth;EXT_shader_texture_lod;EXT_texture_compression_bptc;EXT_texture_compression_rgtc;EXT_texture_filter_anisotropic;EXT_sRGB;KHR_parallel_shader_compile;OES_element_index_uint;OES_fbo_render_mipmap;OES_standard_derivatives;OES_texture_float;OES_texture_float_linear;OES_texture_half_float;OES_texture_half_float_linear;OES_vertex_array_object;WEBGL_color_buffer_float;WEBGL_compressed_texture_s3tc;WEBGL_compressed_texture_s3tc_srgb;WEBGL_debug_renderer_info;WEBGL_debug_shaders;WEBGL_depth_texture;WEBGL_draw_buffers;WEBGL_lose_context;WEBGL_multi_draw,webgl aliased line width range:[1, 1],webgl aliased point size range:[1, 1024],webgl alpha bits:8,webgl antialiasing:yes,webgl blue bits:8,webgl depth bits:24,webgl green bits:8,webgl max anisotropy:16,webgl max combined texture image units:32,webgl max cube map texture size:16384,webgl max fragment uniform vectors:1024,webgl max render buffer size:16384,webgl max texture image units:16,webgl max texture size:16384,webgl max varying vectors:30,webgl max vertex attribs:16,webgl max vertex texture image units:16,webgl max vertex uniform vectors:4095,webgl max viewport dims:[32767, 32767],webgl red bits:8,webgl renderer:WebKit WebGL,webgl shading language version:WebGL GLSL ES 1.0 (OpenGL ES GLSL ES 1.0 Chromium),webgl stencil bits:0,webgl vendor:WebKit,webgl version:WebGL 1.0 (OpenGL ES 2.0 Chromium),webgl unmasked vendor:Google Inc. (NVIDIA),webgl unmasked renderer:ANGLE (NVIDIA, NVIDIA GeForce GTX 1060 3GB Direct3D11 vs_5_0 ps_5_0, D3D11),webgl vertex shader high float precision:23,webgl vertex shader high float precision rangeMin:127,webgl vertex shader high float precision rangeMax:127,webgl vertex shader medium float precision:23,webgl vertex shader medium float precision rangeMin:127,webgl vertex shader medium float precision rangeMax:127,webgl vertex shader low float precision:23,webgl vertex shader low float precision rangeMin:127,webgl vertex shader low float precision rangeMax:127,webgl fragment shader high float precision:23,webgl fragment shader high float precision rangeMin:127,webgl fragment shader high float precision rangeMax:127,webgl fragment shader medium float precision:23,webgl fragment shader medium float precision rangeMin:127,webgl fragment shader medium float precision rangeMax:127,webgl fragment shader low float precision:23,webgl fragment shader low float precision rangeMin:127,webgl fragment shader low float precision rangeMax:127,webgl vertex shader high int precision:0,webgl vertex shader high int precision rangeMin:31,webgl vertex shader high int precision rangeMax:30,webgl vertex shader medium int precision:0,webgl vertex shader medium int precision rangeMin:31,webgl vertex shader medium int precision rangeMax:30,webgl vertex shader low int precision:0,webgl vertex shader low int precision rangeMin:31,webgl vertex shader low int precision rangeMax:30,webgl fragment shader high int precision:0,webgl fragment shader high int precision rangeMin:31,webgl fragment shader high int precision rangeMax:30,webgl fragment shader medium int precision:0,webgl fragment shader medium int precision rangeMin:31,webgl fragment shader medium int precision rangeMax:30,webgl fragment shader low int precision:0,webgl fragment shader low int precision rangeMin:31,webgl fragment shader low int precision rangeMax:30Google Inc. (NVIDIA)~ANGLE (NVIDIA, NVIDIA GeForce GTX 1060 3GB Direct3D11 vs_5_0 ps_5_0, D3D11)falsefalsefalsefalse0,false,falseArial,Arial Black,Arial Narrow,Book Antiqua,Bookman Old Style,Calibri,Cambria,Cambria Math,Century,Century Gothic,Century Schoolbook,Comic Sans MS,Consolas,Courier,Courier New,Georgia,Helvetica,Impact,Lucida Bright,Lucida Calligraphy,Lucida Console,Lucida Fax,Lucida Handwriting,Lucida Sans,Lucida Sans Typewriter,Lucida Sans Unicode,Microsoft Sans Serif,Monotype Corsiva,MS Gothic,MS PGothic,MS Reference Sans Serif,MS Sans Serif,MS Serif,Palatino Linotype,Segoe Print,Segoe Script,Segoe UI,Segoe UI Light,Segoe UI Semibold,Segoe UI Symbol,Tahoma,Times,Times New Roman,Trebuchet MS,Verdana,Wingdings,Wingdings 2,Wingdings 3124.04347527516074'
    buvid_fp = js.call('s', t, 31)
    session.cookies['buvid_fp'] = buvid_fp


def start(aid, cid):
    h5_url = 'https://api.bilibili.com/x/click-interface/click/web/h5'
    data = {
        "aid": aid,
        "cid": cid,
        "part": "1",
        "lv": "0",
        "ftime": int(time.time() * 100),
        "stime": int(time.time() * 100),
        "type": "3",
        "sub_type": "0",
        "refer_url": "",
        "spmid": "333.788.0.0",
        "from_spmid": "333.337.search-card.all.click",
        "csrf": ""
    }
    session.post(h5_url, data=data)


def get_video_id_info(video_url, proxies):
    session = requests.Session()
    bvid = video_url.rsplit('/')[-1]
    res = session.get(
        url="https://api.bilibili.com/x/player/pagelist?bvid={}&jsonp=jsonp".format(bvid),
        proxies=proxies
    )

    cid = res.json()['data'][0]['cid']

    res = session.get(
        url="https://api.bilibili.com/x/web-interface/view?cid={}&bvid={}".format(cid, bvid),
        proxies=proxies
    )
    res_json = res.json()
    aid = res_json['data']['aid']
    view_count = res_json['data']['stat']['view']
    duration = res_json['data']['duration']
    print("\n视频 {}，平台播放量为：{}".format(bvid, view_count))
    session.close()
    return aid, bvid, cid, duration, int(view_count)


def main():
    media_url = 'https://www.bilibili.com/video/BV1N94y1R7K5'
    aid, bvid, cid, duration, view_count = get_video_id_info(media_url, proxies={'http': 'https:127.0.0.1:7890'})
    while True:
        try:
            get_video_id_info(media_url, proxies={'http': 'https:127.0.0.1:7890'})
            aid, cid = req_media(media_url)
            req_v2(aid, cid)
            set_b_lsid()
            set_uuid()
            set_buvid4()
            set_buvid_fp()
            start(aid, cid)
            view_count += 1
            print("理论刷的播放量：", view_count)
        except Exception as e:
            print(e)


if __name__ == '__main__':
    session = requests.session()
    session.headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36'
    }
    main()




